// 存储数据
const setItem = (key, value) => {
  if (typeof value === "object") {
    value = JSON.stringify(value);
  }
  localStorage.setItem(key, value);
};

// 读取数据
const getItem = (key) => {
  const value = localStorage.getItem(key);
  try {
    return JSON.parse(value)
  } catch (e) {
    return value
  }
};

// 删除数据
const removeItem = (key) => {
  localStorage.removeItem(key)
}

// 清空所有数据
const clearAll = () => {
  localStorage.clear()
}

// 检查数据是否存在
const hasItem = () => {
  return localStorage.getItem(key) !== null
}

// 判断设备是否是移动端
const isMobile = () => {
  const userAgent = navigator.userAgent || window.opener;
  const isMobileDevice = /android | iphone |ipad | ipod | windows phone/i.test(userAgent)
  const isSmallScreen = window.matchMedia("(max-width: 767px)").matches

  return isMobileDevice || isSmallScreen
}

export {
  setItem,
  getItem,
  removeItem,
  clearAll,
  hasItem,
  isMobile
}